﻿#ifndef GEOIMAGE_H
#define GEOIMAGE_H

#include <osg/Image>
#include "Extent.h"

using namespace rxtiler;

class GeoImage
{
public:
    GeoImage(void){_raster = 0;}
    GeoImage(osg::Image* r,Extent& e){
        _raster = r;
        _extent = e;
    }

    inline osg::Vec4 getGeoVal(double lon,double lat)
    {
        //函数内部不做范围判断
        //请在外部保证
        double rx = (lon - this->_extent.left ) / (_extent.right - _extent.left);
        double r = lat - _extent.bottom;
        double ry = r / (_extent.top - _extent.bottom);
        //int x = (_raster->x()-1) * rx + 0.5;
        //int y = (_raster->y()-1) * ry + 0.5;

        //return _raster->getVal<T>(x,y,z);

        int x = _raster->s()-1;
        int y = _raster->t()-1;
        rx = x * rx;
        ry = y * ry;

        int it = (int)(rx+0.5);
        int is = (int)(ry+0.5);


        osg::Vec4 v = _raster->getColor(it,is);
        return v;
    }

    void mapfrom( GeoImage& grst )
    {
        int ax = _raster->s()-1;
        int ay = _raster->t()-1;
        for (int y = 0; y <= ay;++y)
        {
            double lat =  (double)y / ay  * (_extent.top - _extent.bottom);
            lat =  _extent.bottom + lat;
            if (grst._extent.containy(lat)){
                for (int x = 0; x <= ax;++x)
                {
                    double lon = (double)x / ax * (_extent.right - _extent.left) + _extent.left;
                    if (grst._extent.containx(lon))
                    {
                        osg::Vec4 v = grst.getGeoVal(lon,lat);
                        this->_raster->setColor(v,x,y);
                    }
                }

            }
        }
    }

protected:
    Extent _extent;
    osg::Image* _raster;
//		bool _lefttop;
};

inline void mapImage(osg::Image *in, Extent& inext, osg::Image *out, Extent &outext){
    if(!in || !out){
        return;
    }
    GeoImage gr1(in,inext);
    GeoImage gr2(out,outext);
    gr2.mapfrom(gr1);
}


#endif // GEOIMAGE_H

